//连接数据库
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/better_me');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log('数据库连接成功ByWGW！');
});

function build_notebook(name){
    return db.model(name,{
        title:{type:String},
        contents:{type:Object}
    });
}
let book_model=build_notebook('notebook');
const createNoteBook=postData=>{
    const insertObj=new book_model(postData);
    console.log(insertObj);
    return insertObj.save()
    .then(res=>{
        return res;
    })
    .catch(err=>{
        console.log('插入失败',err);
        return false;
    })
}
const searchNoteBook=(obj)=>{
    return book_model.find(obj)
    .then(res=>{
        return res;
    })
    .catch(err=>{
        console.log('查询失败',err);
        return [];
    })
}
const updateNoteBook=(before,after)=>{
    book_model.findOneAndUpdate(before,after,{},(err,ret)=>{
        if(err) console.log('更新失败');
        else console.log('更新成功');
    })
}
module.exports={
    createNoteBook,
    searchNoteBook,
    updateNoteBook,
}